var express = require('express');
var router = express.Router();
var fs = require('fs')
var multiparty = require('multiparty');
var xlsx = require("node-xlsx").default;
const jwt = require('jsonwebtoken');
const { TypeModel, BusinessModel, GoodModel,UserModule } = require('../mongodb/db')
// const express = require("express");
const multer = require('multer');
const path = require("path")
/* GET home page. */
//获取商品列表
router.get('/shop', async (req, res) => {
    let data = await GoodModel.find()
    res.send({
        code: 200,
        data: data
    })
})
router.get('/type', async (req, res) => {
    let data = await TypeModel.find()
    res.send({
        code: 200,
        data: data
    })
})
//获取商家列表
router.get('/business', async (req, res) => {
    let data = await BusinessModel.findOne()
    res.send({
        code: 200,
        data: data
    })
})
//获取商家账号信息
router.get('/business_user',async(req,res)=>{
  let data = await UserModule.findOne({_id:'67b589e7a903f46a31f27d4b'})
  console.log(data);
  res.send({
      code: 200,
      data: data
  })
})
//修改商家账号信息
router.post('/update_business',async(req,res)=>{
  let { username, phone } = req.body
  // console.log(user,phone);
  await UserModule.updateOne({_id:'67b589e7a903f46a31f27d4b'},{username:username,phone:phone})
  res.send({
      code: 200
  })
})
//商品上下架
router.post('/update', async (req, res) => {
    let { item, val } = req.body
    console.log(item, val);
    let id = item._id
    await GoodModel.updateMany({ _id: id }, { issale: !val })
    res.send({
        code: 200
    })
})
//商品批量上架
router.post('/shang', async (req, res) => {
    await GoodModel.updateMany({ issale: true })
    res.send({
        code: 200
    })
})
//商家状态
router.post('/unstatus', async (req, res) => {
    await BusinessModel.updateMany({ status: false })
    res.send({
        code: 200
    })
})
router.post('/status', async (req, res) => {
    await BusinessModel.updateMany({ status: true })
    res.send({
        code: 200
    })
})
//上传公告
router.post('/shangchuan', async (req, res) => {
    let { value } = req.body
    await BusinessModel.updateMany({ gonggao: value })
})
//商家充值余额
router.post('/chongzhi',async(req,res)=>{
    let { amount } = req.body
    let data = await BusinessModel.findOne()
    let yue = Number(data.total)+Number(amount)
    data.record.unshift({'type':"充值","money":amount,"time":new Date(),"yue":yue})
    console.log(data.record);
    await BusinessModel.updateMany({$inc:{"total":amount},$set:{"record":data.record}})
    res.send({
        code: 200
    })
})
//修改团购
router.post('/group', async (req, res) => {
  let {item} = req.body
  await GoodModel.updateMany({ _id: item._id }, { isgroup: !item.isgroup })
  res.send({
      code: 200
  })
})
///////////////////////////////////////////////////////////////////////
//上传图片开始
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads/'); // 文件保存到 uploads 目录
    },
    filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      cb(null, uniqueSuffix + path.extname(file.originalname)); // 生成唯一文件名
    },
  });
  
  // 初始化上传中间件
  const upload = multer({ storage });
  
  // 文件上传接口
  router.post('/xu_uploads', upload.single('file'), (req, res) => {
    if (!req.file) {
      return res.status(400).json({ code: 400, message: '未上传文件' });
    }
    // 返回文件路径
    res.send({
      code: 200,
      message: '上传成功',
      data: {
        filePath: `/uploads/${req.file.filename}`, // 文件访问路径
      },
    });
  });
  
  router.post('/putUserHead', async (req, res) => {
    try {
      await BusinessModel.updateOne({ $set: { img1: req.body.head } })
      res.send({
        code: 200,
        message: "修改成功"
      })
    } catch (error) {
      console.log(error);
      res.send({
        code: 500,
        message: '修改失败',
      })
    }
  });
//结束

//////////////////////////////////////////////////////////////////////
//支付宝沙箱
const bodyParser = require('body-parser');
const AlipaySdk = require('alipay-sdk').default;
const cors = require('cors');
// const app = express();
const app = express();
app.use(cors({
    origin: 'http://localhost:5173', // 仅允许来自这个源的请求
    credentials: true // 如果需要发送凭证（如 cookies）
}));

app.use(bodyParser.json());

// 初始化支付宝 SDK
const alipaySdk = new AlipaySdk({
    appId: '9021000144618631', // 替换为你的沙箱 AppID
    privateKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC86lEoOrDIiudV2INd2owB0V7vWsCXWTjW2scNi0/b+EGTHj9PitI3Qcznfxqt2TRPpdcOMKWcmv763p4Hk3KM97XgZeyTU4ge+OWYBZPnueeftEAsHpMnuuacetRtXx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MI8qn3ugcV188zQKBgCsopc2vfxNXZiU7BqgNAL35w/elV3Dub1SeWKtaGe9ug/3eKI1ZIgIXJ0mLa5Y9sotkhGzLBcRdjBlnlVugBvJgP68qgswFVJoxztmyPl0CDdLrDxMXgYwYkpfyD/rDaWh1vP0h37s/iKuTvPdanjFCcvLNAZSjxY3AProvZX4hAoGACMWUnt0BFfXnBuIV2aqyxpicL/3df3pIRqd0dudJuISKGUUJUXm3idGT8aPcA0U6l4Z2AquJOjqnbG8EojlTaslnuj9SGVwo3af/ySbnhEqqGVbZfNrx2bS3dulLYZzRGUXXHCxKTuWj1Xw/3ZJUIJvPvcLjypV1254bPNWZkOk=', // 替换为你的私钥
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg+zLB2LHHYfOjjLBOi0XUL1Vis49/VD5ZbFMgVhSAo4IAQ/5ArKR6af126MXH21o4iqoniYOBsIVGwPO82qYGv8FXzA1fWzD5A6xRApSL/ssLFnCXCzRrKEk0sU0yV6PCfyKXzv29ZiZ/cKGclk+C/jlIOa/W3U786axLs8mD0wB+HSXdmyjuBf5G6yZnKUYt+FmmY3uCGmdeIhCOnxZ0ud/chlQJPIBY4tfQ6W6vMLpdFEy/9t01s//JQ1btWhsyLF67rXC7x7QAZkckUvEhBprHQgNS4R6WdlVhrj1cOi0SnguLp9FCnGvbbEYH535/82wvIxW0fpWvuY9aUq7zQIDAQAB', // 替换为支付宝返回的公钥
    gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱环境网关
});

router.get('/createOrder', async (req, res) => {
    const outTradeNo = Date.now().toString(); // 生成订单号
    let qian = req.query.qian
    const amount = qian; // 支付金额（单位：元）
    // const amount = 200
    const result =  alipaySdk.pageExec('alipay.trade.wap.pay', { // 修改为移动端支付接口
        method: 'GET',
        bizContent: {
            out_trade_no: outTradeNo, // 订单号
            product_code: 'QUICK_WAP_WAY', // 修改为移动端支付产品码
            total_amount: amount, // 支付金额
            subject: '余额充值', // 商品名称
            body: '充值', // 商品描述
        },
        return_url: 'http://localhost:5173/money', // 支付成功后的回调地址
        notify_url: 'http://localhost:3000/notify', // 支付结果异步通知地址
    });

    res.send(result);
});

app.listen(3002, () => {
    console.log('Server is running on http://localhost:3002');
});




module.exports = router;
